<template>
    <view class="page-activity-detail">
        <view class="banner" @click="isFullImage = !isFullImage">
            <u-image v-if="isFullImage" width="100%" mode="widthFix" :src="apiUrl + info?.coverImageUrl"></u-image>
            <u-image v-else width="100%" height="358rpx" :src="apiUrl + info?.coverImageUrl"></u-image>
            <text class="tips">{{isFullImage ? '点击收起' : '点击查看全部'}}</text>
        </view>
        <view class="info fly-card mb-2">
            <view class="content mx-4">
                <view class="title font-bold">{{ info?.activitiesName }}</view>
                <view class="flex-between mt-2 mb-3">
                    <view class="tags">
                        <u-tag class="tag-noborder mr-1" :class="'activity-tag-' + info?.activitiesType" :text="proxy.$util.setName(info?.activitiesType, optionData.activitiesType)" />
                        <u-tag class="tag-red tag-noborder" text="签到" v-if="info?.isCheckinRequired == '1'" />
                        <u-tag class="tag-green tag-noborder ml-1" plain text="已报名" v-if="isDo.isRegister"></u-tag>
                        <u-tag class="tag-green tag-noborder ml-1" plain text="已候补" v-if="isDo.isAlternate"></u-tag>
                    </view>
                    <view class="grey9" v-if="info?.activitiesMethod == '1' && isDo.isLocation"><u-icon name="map"></u-icon>{{proxy.$util.getDistance(info?.latitude, info?.longitude, location?.latitude, location?.longitude)}}km</view>
                </view>
                <view class="desc">
                    <view>创建人：<text class="c-grey3">{{ info.initiatorUserName }}</text></view>
                    <view v-if="Number(info?.amount) > 0">费用：<text class="c-grey3">{{ info.amount }} 元</text></view>
                    <view class="flex-between">
                        <view>报名：<text class="c-grey3">{{signList.length}}/{{ info?.maxParticipants }}</text></view>
                        <u-tag v-if="isDo.isManager" class="tag-cyan" type="primary" text="管理" shape="circle" size="mini" @click="proxy.$util.gotoPage('/packageB/activity/manage', {id: info.id})"></u-tag>
                    </view>
                    <view>时间：<text class="c-grey3">{{ info?.startTime }} {{ info?.week }}</text></view>
                    <view class="flex-between" @click="openMap">
                        <view class="mr-4">地址：<text class="c-grey3">{{ info?.address  || '线上' }}</text></view>
                        <u-image v-if="info?.activitiesMethod == '1'" :src="proxy.$icon.navigation" width="40rpx" height="40rpx"></u-image>
                    </view>
                </view>
            </view>
        </view>
        <view class="sign">
            <view class="intro">
                <!-- <view class="fly-title">内容简介</view> -->
                <view class="flex-block title">
                    <u-image :src="proxy.$icon.brief" width="48rpx" height="48rpx"></u-image>
                    <text class="ml-2">内容简介</text>
                </view>
                <view class="c-grey6 mt-2">{{ info?.description }}</view>
                <!-- <view class="fly-title">推荐语&备注</view> -->
                <view class="flex-block title pt-4">
                    <u-image :src="proxy.$icon.remarks" width="48rpx" height="48rpx"></u-image>
                    <text class="ml-2">推荐语&备注</text>
                </view>
                <view class="c-grey6 mt-2">{{ info.recommendations }}</view>
            </view>
        </view>
        <view class="tab">
            <u-tabs :list="tab.list" :is-scroll="false" v-model="tab.current" active-color="#24BCB8" @change="changeTab"></u-tabs>
            <view class="tab-content">
                <view class="tab-1" v-show="tab.current == 0">                    
                    <u-cell-group :border="false">
                        <u-cell-item v-for="(item,index) in signList" :key="index" :arrow="false" :border-bottom="signList.length - 1 == index ? false : true">
                            <template #icon>
                                <u-image width="88rpx" height="88rpx" :src="item.appUserListVo.avatar ? proxy.$util.getFullImage(item.appUserListVo.avatar) : proxy.$icon.avatar" shape="circle" @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: item.userId })"></u-image>
                            </template>
                            <view slot="title" class="ml-2" @click="proxy.$util.gotoPage('/packageB/bolg/index', { userId: item.userId })">
                                {{ item.appUserListVo.nickname || item.appUserListVo.username }}
                                <u-icon v-if="item.role.indexOf('HOST') != -1" class="c-cyan" name="mic"></u-icon>
                            </view>
                            <template v-if="isDo.startVote">
                                <u-button size="mini" class="btn-deepCyan" shape="circle" @click="activityVotes(0,item)" v-if="!isDo.isOver && isDo.isVote">投票</u-button>
                            </template>
                            <template v-else>
                                <u-button size="mini" class="btn-grey" shape="circle">投票未开始</u-button>
                            </template>
                            <template v-if="isDo.isOver">
                                <u-tag class="tag-cyan" v-if="item.role.indexOf('SPEAKERS') != -1" text="最佳发言人" shape="circle"></u-tag>
                            </template>
                        </u-cell-item>
                    </u-cell-group>
                </view>
                <view class="tab-2" v-show="tab.current == 1">
                    <view class="fly-title">1、自我介绍</view>
                    <view class="c-grey6">轮流自我介绍，可以在活动小群内发出自己的发言序号，帮助大家互相认识。由主持人开始，主持人序号为1，采用顺时针顺序。</view>
                    <view class="fly-title">2、问题讨论</view>
                    <view class="c-grey6">Q1 {{ info.discussionQuestions1 }}</view>
                    <view class="c-grey6">Q2 {{ info.discussionQuestions2 }}</view>
                    <view class="c-grey6">Q3 {{ info.discussionQuestions3 }}</view>
                    <view class="fly-title">3、最佳投选</view>
                    <view class="c-grey6">根据前面的发言，在小程序【活动成员】页面投选最佳发言者，投给你认为的本场最佳发言者，大家投完后由主持人宣布票数第一名,</view>
                    <view class="fly-title">关于“申请成为主持人”</view>
                    <view class="font-bold">·每位参与者都可以成为主持人</view>
                    <view class="mt-2 c-grey6">报名本次活动的每位成员都可以成为主持人。主持人不需要额外准备，主要是现场引导大家进入流程、安排发言顺序、提示大家不要偏离话题。主持人也要参与全程的问题讨论</view>
                    <view class="font-bold mt-2">·成为主持人的益处</view>
                    <view class="mt-2 c-grey6">主持人在现场会受到更多的关注，更能被大家认识和了解，同时也可以锻炼表达和场控能力。主持人可以修改讨论问题，主导读书会。</view>
                    <view class="font-bold mt-2">·每场一位主持人</view>
                    <view class="mt-2 c-grey6">非常鼓励大家表达和展现自己。这是一个非常好的的场景去练习表达能力，欢迎大家踊跃成为主持人，点击右下角【成为主持人】按钮即可，主持人只有一位，先来先得。</view>
                </view>
                <view class="tab-3 text-center" v-show="tab.current == 2">
                    <u-image width="400rpx" height="400rpx" :src="apiUrl + info.groupQrcodeUrl" class="inline-block"></u-image>
                    <view class="mb-8">群二维码</view>
                    <u-image width="400rpx" height="400rpx" :src="apiUrl + info.organizerWechatQrcodeUrl" class="inline-block"></u-image>
                    <view>发起人二维码</view>
                </view>
                <view class="tab-4 fly-card" v-show="tab.current == 3">
                    <view class="p-4" v-if="tab.commentList.length == 0">
                        <u-empty text="暂无内容" mode="list"></u-empty>
                    </view> 
                    <template v-else>
                        <view class="item" v-for="(item,index) in tab.commentList" :key="index">
                            <view class="thumb">
                                <u-image width="48rpx" height="48rpx" :src="proxy.$util.getFullImage(item.appUserListVo.avatar)" shape="circle"></u-image>
                            </view>
                            <view class="content">
                                <view class="title">{{ item.appUserListVo.nickname || item.appUserListVo.username }}</view>
                                <view class="desc"><view v-html="proxy.$util.resetHtml(item.content)"></view></view>
                            </view>
                        </view>
                    </template>
                </view>
            </view>
        </view>
        <view class="fly-bottom-bar" v-if="Number(info.status) >1">
            <view class="flex-between content">
                <!-- <view class="align-center c-red" style="width:100%;" v-if="userInfo.isExpire">
                        会员已过期，续费后才可参加活动
                </view>
                <template v-else> -->
                <view class="fl flex-between">
                    <view class="icon-share">
                        <button open-type="share" class="btn-share"></button>
                        <u-image :src="proxy.$icon.share2" width="48rpx" height="48rpx"></u-image>
                        <view>分享</view>
                    </view>
                    <view class="icon-alternate" @click="activityAlternate" v-if="isDo.isFull && !isDo.isRegister">
                        <u-image  :src="isDo.isAlternate ? proxy.$icon.alternatPre : proxy.$icon.alternateDef" width="48rpx" height="48rpx"></u-image>
                        <view>{{isDo.isAlternate ? '取消候补' : '候补'}}</view>
                    </view>
                    <view class="icon-sign" @click="checkIn" v-if="info.isCheckinRequired == '1' && isDo.isRegister">
                        <u-image :src="isDo.isChecking ? proxy.$icon.signinPre : proxy.$icon.signin" width="48rpx" height="48rpx"></u-image>
                        <view>{{isDo.isChecking ? '已签到' : '签到'}}</view>
                    </view>
                </view>
                <view class="fr flex-between">       
                    <template v-if="isDo.isOver">
                        <view class="btn grey" style="width:100%">活动已结束</view>
                    </template>
                    <template v-else>
                        <template v-if="isDo.isExpire">
                            <view class="btn grey" style="width:100%">活动已停止报名</view>
                        </template>
                        <template v-else>           
                            <template v-if="isDo.isRegister">
                                <view class="btn grey" v-if="isDo.hadHost">主持人已定</view>
                                <view class="btn cyan" v-else @click="activityVotes(1)">成为主持人</view>
                                <view class="btn deepCyan" @click="cancelRegister">取消报名</view>
                            </template>
                            <template v-else>
                                <template v-if="isDo.isFull">
                                    <view class="btn grey" style="width:100%">已达报名人数</view>
                                </template>
                                <template v-else>
                                    <view class="btn deepCyan" @click="activityRegistrations('activities')">报名活动</view>
                                </template>
                            </template>
                            <!-- <view class="btn grey" v-if="isDo.hadHost">主持人已定</view>
                            <view class="btn cyan" v-else @click="activityVotes(1)">成为主持人</view>
                            <view class="btn deepCyan" @click="activityRegistrations">
                                <text v-if="!isDo.isRegister && isDo.isFull">已满员</text>
                                <text v-else>{{ isDo.isRegister ? '已报名' : '报名活动' }}</text>                        
                            </view> -->
                        </template>
                    </template>
                </view>
                <!-- </template> -->
            </view>
        </view>

    </view>
</template>
<script setup lang="ts">
import {apiUrl} from '@/static/js/config';
import dayjs from 'dayjs';
import {onShow, onLoad, onShareAppMessage} from '@dcloudio/uni-app';
import { useAppStore } from '@/stores/app';
import { useOptionData } from '@/stores/optionData';
const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const appStore = useAppStore();
const optionDataStore = useOptionData();
let isLogin = ref(false);
let pageParams = reactive({});
let location = reactive({});
let userInfo = ref();
let info = ref({});
let signList = ref([]); // 已报名列表
let signNum = ref(0); // 已报名人数 + 已候补人数
let registrations = ref({});
let isFullImage = ref(false);
let tab = reactive({
    list:[
        {name: '活动成员'},
        {name: '活动流程'},
        {name: '群二维码'},
        {name: '相关笔记'}
    ],
    current: 0,
    commentList: [],
});
let isDo = reactive({
    isLocation: false, // 是否显示距离
    isChecking: false, //是否已签到
    isRegister: false, //是否已报名
    isHost: false, //是否是主持人，
    hadHost: false, // 是否已经有主持人,
    isFull: false, // 是否满员,
    isAlternate: false, // 是否已候补
    isExprie: false, // 是否已过期
    isOver: false, // 是否已结束
    isVote: false, // 是否可以投票，当前用户在报名列表里才可以投票
    isManager: false, // 当前用户是否是该活动分会长
    startVote: false, // 是否开始投票
    role: null, // 角色（INITIATOR: 发起人, HOST: 主持人, MEMBER: 普通会员，SPEAKERS：最佳发言人），多个:隔开
});
let optionData = reactive({
    activitiesType: [],
});
const getInitData = async () => {
  let activitiesType = await optionDataStore.getDictList('activitie_type');
  optionData.activitiesType = activitiesType;
}
const getDetail = () => {
    proxy.$http('get', '/admin/activities/'+ pageParams.id, {}, (data,msg) => {
        info.value = data;
        // getGuildMember();
        checkManager();
        info.value.week = proxy.$util.getWeekName(dayjs(data.startTime).day());
        isDo.isExpire = dayjs(data.startTime).isBefore(dayjs());
        isDo.isOver = data.status == 4 ? true : false;
        isDo.startVote = dayjs(data.startTime).isBefore(dayjs());
        if(signList.value.length == info.value.maxParticipants){
            isDo.isFull = true;
        }else{
            isDo.isFull = false;
        }
    });
};
const getListActivities = () => {
    proxy.$http('get', '/admin/activityRegistrations/getListActivities/'+ pageParams.id, {}, (data,msg) => {
        signNum.value = data.length;
        signList.value = data.filter(item => item.status == '0');
        let alternateList = data.filter(item => item.status == '1');
        if(signList.value.length == info.value.maxParticipants){
            isDo.isFull = true;
        }else{
            isDo.isFull = false;
        }
        isDo.hadHost = signList.value.some(item => item.role.indexOf('HOST') != -1);
        isDo.isVote = signList.value.some(item => item.userId == appStore.userInfo.userId);
        isDo.isAlternate = alternateList.some(item => item.userId == appStore.userInfo.userId);
        // console.log(isDo, signNum.value, signList.value.length)
    })
}
const changeTab = (i) => {
    console.log(i)
};
const getNote = () => {
    proxy.$http('get', '/admin/articles/page', {current:1, size:10, activitiesId: pageParams.id}, (data,msg) => {
        tab.commentList = data.records;
    })
}
const openMap = () => {
    if(info.activitiesMethod == '0'){
        return;
    }
    const latitude = info.value.latitude;
    const longitude = info.value.longitude;
    uni.openLocation({
        latitude,
        longitude,
        scale: 18
    });
};
const getMyActivity = () => {
    proxy.$http('get', '/admin/activityRegistrations/getUserActivities/'+ pageParams.id, {}, (data,msg) => {
        registrations.value = data || {};
        if(data){
            isDo.isRegister = data.status == '0' ? true : false;
            isDo.isChecking = data.isChecking == '1' ? true : false;
            isDo.role = data.role;
        }else{
            isDo.isRegister = false;
            isDo.isChecking = false;
            isDo.role = null;
        }
    })
}
const checkIn = () => {
    uni.getLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success (res) {
            let params = {
                userId: appStore.userInfo.userId,
                activityId: pageParams.id,
                location: '',
                latitude: res.latitude,
                longitude: res.longitude
            }
            proxy.$http('post', '/admin/checkins', params, (data,msg)=> {
                uni.$u.toast('签到成功');
                getMyActivity();
            },msg => {
            })  
        },
        fail: error => {
            console.log(error)
        }
    });
};
const activityVotes = (type, item) => {
    let params = {
        activityId: pageParams.id,
        votedUserId: appStore.userInfo.userId,
        type: type, // 0：最佳发言人，1;最佳支持人
    };
    let title =  '提交成功！';
    if(type == 0){
        params.votedUserId = item.userId;
        title = '投票成功！';
    }
    proxy.$http('post', '/admin/activityVotes', params, (data,msg) => {
        uni.$u.toast(title);
        getListActivities();
    })
}
const activityRegistrations = (type) => {
    if(!proxy.$util.checkLogin()){
        return;
    }
    if(isDo.isFull && type == 'activities'){ //满员，不能报名
        return;
    }
    if(isDo.isRegister){ // 已报名
        return;
    }
    if(info.value.activitiesType != '3'){
        if(appStore.userInfo.isExpire){
            appStore.checkExpire();
            return;
        }
    }
    let params = {
        activityId: pageParams.id,
        userId: appStore.userInfo.userId,
        status: 0, //0正常，1候补
    };
    if(info.value.amount == 0){
        submitRegistrations(params);
    }else{
        toPay(type);
    }
    
};
const activityAlternate = () => {
    if(isDo.isAlternate){ //已候补，取消报名
        cancelRegister()
    }else{
        activityRegistrations('activitiesHouBu');
    }    
}
const toPay = (type) => {
    if(!appStore.userInfo.userId){
        proxy.$util.checkLogin();
        return;
    }
	uni.login({
		success: response => {
            let strBody = {type: type, userId: appStore.userInfo.userId};//type:正常报名'activities',候补报名'activitiesHouBu'
            let params  = {
                body: JSON.stringify(strBody), // new新开卡，xu续费
                userId: appStore.userInfo.userId,
                relationshipId: info.value.id,
                code: response.code
            };
            appStore.wechatPay(params).then(res => {
                uni.requestPayment({
                    provider: 'wxpay',
                    ...JSON.parse(res),
                    success: successRres => {
                        // 注册并支付后，开始登录成功并跳转
                        uni.$u.toast('报名成功');
                        getMyActivity();
                        getListActivities();
                    }, 
                    error: err => {
                    
                    }
                })
            })			
		},
		fail: () => {
			reject()
		}
	})    
};
const submitRegistrations = (params) => {
    let tips = '报名成功!';
    if(isDo.isFull){
        tips = '候补申请已提交！';
        params.status = 1;
    }
    proxy.$http('post', '/admin/activityRegistrations', params , (data,msg) => {
        uni.showModal({
            title: '提示',
            content: tips,
            showCancel: false,
            success: res => {
                
            }
        })
        getMyActivity();
        getListActivities();
    },msg => {
        
    });
};
const cancelRegister = () => {
    let tips = '确定要取消报名吗？';
    let resTips = '取消成功！';
    if(isDo.isAlternate){
        tips = '确定要取消候补吗？';
    }
    if(Number(info.value.amount)> 0){
        if(isDo.isAlternate){
            resTips = '取消成功，稍后会收到退款！';
        }else{
            resTips = '取消成功，审核后会收到退款！';
        }
    }
    uni.showModal({
        title: '提示',
        content: tips,
        success:res => {
            if(res.confirm){
                proxy.$http('delete', '/admin/activityRegistrations/'+registrations.value.registrationId, {}, (data,msg)=> {
                    uni.showModal({
                        title: '提示',
                        content: msg || resTips,
                        showCancel: false,
                    });
                    getMyActivity();
                    getListActivities();
                });
            }
        }
    })
};
const getGuildMember = () => {
    proxy.$http('get', '/admin/userGuilds/getGuildsMemberInfo/'+ info.value.guildId, {}, (data,msg) => {
        let obj = data.find(item => item.roleId == 2);
        if(obj.userId == appStore.userInfo.userId){
            isDo.isManager = true;
        };
    })
};
const checkManager = () => {
    if(proxy.$util.checkLogin('nologin')){
        appStore.getUserRole().then( async res => {
            if(res.indexOf(3) == -1){
                let list1 = [],list2 = [];
                if(res.indexOf(2) != -1){
                    list1 = await proxy.$http('get', '/admin/guilds/getGuildsByUserId', {});
                }
                if(res.indexOf(1) != -1){
                    list2 = await proxy.$http('get', '/admin/guilds/getFenHUiGuildsByUserId', {});
                }
                let list = list1.concat(list2);
                isDo.isManager = list.some(item => item.guildId == info.value.guildId);
                console.log(isDo.isManager);
            }
        })
    }
}
onLoad((e) => {
    pageParams = e;
});
onShow(() => {    
    console.log(pageParams);
    getInitData();
    appStore.getLocation().then(res => {
        location = appStore.currentLocation;
        getDetail();
        isDo.isLocation = true;
    }).catch(err => {
        isDo.isLocation = false;
        getDetail();
    });
    if(proxy.$util.checkLogin('nologin')){
        isLogin.value = true;
        // userInfo.value = appStore.userInfo;
        appStore.getUserInfo().then(res => {    
            userInfo.value = appStore.userInfo;
            console.log(userInfo.value);
            getListActivities();
            getMyActivity();
            getNote();
        })
        
    }else{
        isLogin.value = false;
    }
})
onShareAppMessage((option) =>{
	// let invite_info = this.$store.state.invite_info
	return {
		title: info.value.activitiesName,
		path: 'packageB/activity/detail?id='+ pageParams.id,
		// imageUrl: invite_info.image_path
	};
});

</script>